﻿using AutoStockTrade.Model;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace AutoStockTrade
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        public IUnityContainer Unity { get { return CacheSingleton.Instance.GetUnityContainer(); } }

        private List<StockModel> _succeedList = null;
        private List<StockModel> SucceedList
        {
            get
            {
                if (_succeedList == null)
                {
                    _succeedList = new List<StockModel>();
                }
                return _succeedList;
            }
        }

        public Form1()
        {
            InitializeComponent();
        }

        private IGetData _getData = null;
        public IGetData GetData
        {
            get
            {
                if (_getData == null)
                {
                    _getData = Unity.Resolve<IGetData>();
                    if (_getData == null)
                    {
                        throw new ApplicationException("Unity Resolve Failed.");
                    }
                }
                return _getData;
            }
        }

        private IStockOperation _stockOperation = null;
        public IStockOperation StockOperation
        {
            get
            {
                if (_stockOperation == null)
                {
                    _stockOperation = Unity.Resolve<IStockOperation>();
                    if (_stockOperation == null)
                    {
                        throw new ApplicationException("Unity Resolve Failed.");
                    }
                }
                return _stockOperation;
            }
        }

        //private SendDataPrensenter sendData = new SendDataPrensenter();

        private Dictionary<string, StockModel> _list;
        public Dictionary<string, StockModel> Cache
        {
            get
            {
                if (_list == null)
                {
                    _list = new Dictionary<string, StockModel>();
                }
                return _list;
            }
            set
            {
                _list = value;
            }
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            this.Timer.Enabled = true;
            this.Timer.Start();
            //List<StockModel> list = Cache.Values.ToList();
            //List<StockModel> buyList = list.FindAll(x => x.Operation.Equals(Operation.Buy));
            //this.Buy(buyList);

            //List<StockModel> sellList = list.FindAll(x => x.Operation.Equals(Operation.Sell));
            //this.Sell(sellList);

        }

        private void Buy(StockModel item)
        {
            //IntPtr hWnd1 = FindWindow(null, "网上股票交易系统5.0");
            //SetForegroundWindow(hWnd1);
            //SendKeys.Send("{Esc}");
            //SendKeys.SendWait("{F1}");

            //foreach (var item in list)
            //{
            //    if (item.Operation == Operation.Buy)
            //    {
            if (!this.CanRepeatCheckBox.Checked)
            {
                if (this.SucceedList.FindAll(x => x.Code.Equals(item.Code) && x.Operation.Equals(Operation.Buy)).Count > 0)
                {
                    return;
                }
            }

            int buyMax = (int)this.StockCountMaxNumericUpDown.Value;
            if (buyMax > 0)
            {
                int boughtCount = this.SucceedList.FindAll(x => x.Operation == Operation.Buy).Count;
                if (boughtCount >= buyMax)
                {
                    return;
                }
            }

            StockOperation.buy_Stock(item.Code, item.Price.ToString(), item.Quantity.ToString(), 0);
            this.SucceedList.Add(item);
            //Thread.Sleep(500);
            //    }
            //}
        }

        private void Sell(StockModel item)
        {
            //IntPtr hWnd1 = FindWindow(null, "网上股票交易系统5.0");
            //SetForegroundWindow(hWnd1);
            //SendKeys.Send("{Esc}");
            //SendKeys.SendWait("{F2}");

            //foreach (var item in list)
            //{
            //    if (item.Operation == Operation.Buy)
            //    {
            StockOperation.sell_Stock(item.Code, item.Price.ToString(), item.Quantity.ToString(), 0);
            //    }
            //}
            this.SucceedList.Add(item);
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            this.Timer.Enabled = false;

            //删除非今日的成交记录
            ClearNotTodaySucceedStock();

            #region Log 保存
            foreach (var item in array)
            {
                string code = item.Code;
                if (Cache.ContainsKey(code))
                {
                    Cache[code] = item;
                }
                else
                {
                    Cache.Add(code, item);
                }
            }

            string path = @"C:\log.xml";
            StockCollection collection = new StockCollection();
            collection.Id = Guid.NewGuid().ToString();
            collection.Name = "Test";
            collection.Code = "Test";
            if (Cache.Values != null && Cache.Values.Count > 0)
            {
                collection.Models = Cache.Values.ToList();
            }

            Util.XMLSerializer<StockCollection>(path, collection);
            #endregion

            if (this.StockOperation.IsBusy)
            {
                this.Timer.Enabled = true;
                return;
            }

            StockModel[] array = this.FilterNotTodoy(GetData.GetData());

            StockModel[] sellArray = this.GetSellArray(array);

            StockModel[] buyArray = this.GetBuyArray(array);

            if (!sellArray.IsEmpty())
            {
                foreach (var item in sellArray)
                {
                    this.Sell(item);
                }
            }

            if (!buyArray.IsEmpty())
            {
                foreach (var item in sellArray)
                {
                    this.Buy(item);
                }
            }

            this.Timer.Enabled = true;
        }

        private void StopButton_Click(object sender, EventArgs e)
        {
            this.Timer.Enabled = false;
            this.Timer.Stop();
        }

        private StockModel[] FilterNotTodoy(StockModel[] array)
        {
            if (array == null || array.Length == 0)
            {
                return array;
            }

            //缺陷 如果是上一个或者下一个月的同一天 可能数据错误.
            var tmpArray = array.ToList<StockModel>().FindAll(x => x.Time.Day.Equals(DateTime.Now.Day)).ToArray();

            return tmpArray;
        }

        private StockModel[] GetSellArray(StockModel[] array)
        {
            if (array == null || array.Length == 0)
            {
                return array;
            }

            return array.ToList().FindAll(x => x.Operation == Operation.Sell).ToArray();
        }

        private StockModel[] GetBuyArray(StockModel[] array)
        {
            if (array == null || array.Length == 0)
            {
                return array;
            }

            return array.ToList().FindAll(x => x.Operation == Operation.Buy).ToArray();
        }

        private void ClearNotTodaySucceedStock()
        {
            if (this.SucceedList.IsEmpty())
            {
                return;
            }
            //缺陷 如果是上一个或者下一个月的同一天 可能数据错误.
            int today = DateTime.Now.Day;
            List<StockModel> delList = new List<StockModel>();
            foreach (var item in this.SucceedList)
            {
                if (!item.Time.Day.Equals(today))
                {
                    delList.Add(item);
                }
            }

            if (!delList.IsEmpty())
            {
                foreach (var item in delList)
                {
                    this.SucceedList.Remove(item);
                }
            }
        }
    }
}
